<template>
  <div class="app-container">
    <template v-if="!showDetailIndex">
      <div class="search-container">
        <el-form ref="form" :model="queryParams" :inline="true">
          <el-form-item prop="sampleNumber" label="样本编号">
            <el-input v-model="queryParams.sampleNumber" placeholder="样本编号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item prop="status" label="样本状态">
            <el-select v-model="queryParams.status" placeholder="样本状态" @change="updateStatus">
              <el-option label="已创建" value="CREATE"></el-option>
              <el-option label="待寄出" value="TO_BE_SENT_OUT"></el-option>
              <el-option label="已寄出" value="SENT_OUT"></el-option>
              <el-option label="样本已收到" value="SAMPLE_RECEIVE"></el-option>
              <el-option label="实验室测序完成" value="REPORT_SEQ_END"></el-option>
              <el-option label="数据分析中" value="DATA_ANALYSIS"></el-option>
              <el-option label="样本审核中" value="REPORT_AUDIT"></el-option>
              <el-option label="完成" value="COMPLETED"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-card shadow="never">
        <template #header>
          <el-button type="success" @click="openDialog()"><i class="el-icon-circle-plus"></i> 新增</el-button>
          <el-button type="success" @click="exportSample()"><i class="el-icon-circle-plus"></i> 导出样本</el-button>
          <el-button type="danger" :disabled="ids.length === 0" @click="handleDelete()"><i
              class="el-icon-delete"></i>删除</el-button>
        </template>
        <el-table v-loading="loading" :data="dataList" highlight-current-row border :cell-style="cellStyle"
          @cell-click="openDetail" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" width="55" prop="dataIndex" />
          <el-table-column label="样本编号" prop="number">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.available" size="medium">{{ scope.row.number }}</el-tag>
              <el-tag v-else type="info" size="medium">{{ scope.row.number }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="用户" prop="userName" />
          <el-table-column label="手机号" prop="phone" />
          <el-table-column label="样本状态" prop="statusText" />
          <el-table-column label="销售人员" prop="saleUserName" />
          <el-table-column label="关联vip" prop="vipCardInfo" />
          <el-table-column label="更新时间" prop="updateTimeText" />
          <el-table-column fixed="right" label="操作" min-width="400" width="400">
            <template #default="scope">
              <el-button type="primary" size="small" link @click="openDetailProcess(scope.row)">查看</el-button>
              <el-button type="warning" size="small" link @click="openDialog(scope.row.id)">编辑</el-button>
              <el-button type="warning" size="small" link @click="openBindSampleDialog(scope.row)"
                v-if="scope.row.status == 'CREATE'">绑定样本</el-button>
              <el-button type="primary" size="small" link @click="openExpressDialog(scope.row)"
                v-if="scope.row.status == 'TO_BE_SENT_OUT'">呼叫快递</el-button>
              <el-button type="warning" size="small" link @click="cancelExpress(scope.row)"
                v-if="scope.row.status == 'SENT_OUT'">取消快递</el-button>
              <el-button type="primary" size="small" link @click="labSignDialog(scope.row)"
                v-if="scope.row.status == 'SENT_OUT'">实验室签收</el-button>
              <!-- <el-button type="danger" size="small" link @click="handleDelete(scope.row.id)"
                v-if="isAdmin || scope.row.status == 'CREATE'">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>

        <div class="block">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryParams.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="10"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </div>
      </el-card>

      <el-dialog :visible.sync="detailProcessDialog.visible" :title="detailProcessDialog.title" width="500px"
        :before-close="closeDetailProcessDialog">
        <div style="margin-bottom: 10px;">
          <p><span>样本编号：</span><span>{{ checkedSample.number }}</span></p>
          <p style="margin-top: 8px;"><span>样本状态：</span><span>{{ checkedSample.statusText }}</span></p>
        </div>
        <div style="height: 500px;">
          <el-steps direction="vertical" :active="activeStep">
            <el-step title="已创建" :description="sampleHistoryTimeMap['CREATE']"></el-step>
            <el-step title="待寄出" :description="sampleHistoryTimeMap['TO_BE_SENT_OUT']"></el-step>
            <el-step title="已寄出" :description="sampleHistoryTimeMap['SENT_OUT']"></el-step>
            <el-step title="样本已收到" :description="sampleHistoryTimeMap['SAMPLE_RECEIVE']"></el-step>
            <el-step title="测序完成" :description="sampleHistoryTimeMap['REPORT_SEQ_END']"></el-step>
            <el-step title="数据分析中" :description="sampleHistoryTimeMap['DATA_ANALYSIS']"></el-step>
            <el-step title="样本待审核" :description="sampleHistoryTimeMap['REPORT_AUDIT']"></el-step>
            <el-step title="已完成" :description="sampleHistoryTimeMap['COMPLETED']"></el-step>
          </el-steps>
        </div>
      </el-dialog>

      <el-dialog :visible.sync="detailDialog.visible" :title="detailDialog.title" width="500px"
        :before-close="closeDetailDialog">
        <div>
          <p><span>样本编号：</span><span>{{ checkedSample.number }}</span></p>
          <p style="margin-top: 8px;"><span>样本状态：</span><span>{{ checkedSample.statusText }}</span></p>
          <p style="margin-top: 8px;"><span>更新时间：</span><span>{{ checkedSample.updateTimeText }}</span></p>
          <p style="margin-top: 8px;"><span>创建时间：</span><span>{{ checkedSample.createTimeText }}</span></p>
          <img :src="sampleImgUrl" style="margin-top: 10px; width: 320px;" />
        </div>
      </el-dialog>

      <!-- 样本表单弹窗 -->
      <el-dialog :visible.sync="dialog.visible" :title="dialog.title" width="500px" :before-close="closeDialog">
        <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="100px">
          <el-form-item label="样本个数" prop="num" v-if="!formData.id">
            <el-input-number v-model="formData.num" controls-position="right" :min="1" :max="99"
              size="medium"></el-input-number>
          </el-form-item>
          <el-form-item label="样本产品类型" prop="productType">
            <el-select v-model="formData.productType" placeholder="样本产品类型">
              <el-option label="16S" value="S_16"></el-option>
              <el-option label="宏基因组" value="METAGENOME"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="样本用途" prop="sampleUses">
            <el-select v-model="formData.sampleUses" placeholder="样本用途">
              <el-option label="销售" value="SALE"></el-option>
              <el-option label="试用" value="PROBATION"></el-option>
              <el-option label="测试" value="TEST"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="绑定销售人员" prop="saleUserId">
            <el-select v-model="formData.saleUserId" placeholder="销售人员">
              <el-option v-for="item in saleUserList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属租户" prop="tenantId">
            <el-select v-model="formData.tenantId" placeholder="所属租户">
              <el-option v-for="item in tenantList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户名称" prop="customName">
            <el-input v-model="formData.customName" placeholder="请输入客户名称"></el-input>
          </el-form-item>
          <el-form-item label="销售备注" prop="saleRemark">
            <el-input v-model="formData.saleRemark" placeholder="请输入销售备注" type="textarea" :autosize="{ minRows: 8 }"></el-input>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="addOrUpdate">确 定</el-button>
            <el-button @click="closeDialog">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog :visible.sync="bindSampleDialog.visible" title="绑定样本" width="500px"
        :before-close="closeBindSampleDialog">
        <el-form ref="sampleFormRef" :model="bindSampleFormData" :rules="rules" label-width="100px">
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="bindSampleFormData.userName" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="用户手机号" prop="phone">
            <el-input v-model="bindSampleFormData.phone" placeholder="请输入用户手机号" />
          </el-form-item>
          <el-form-item label="需绑定用户" prop="sysUserId">
            <el-select v-model="bindSampleFormData.sysUserId" placeholder="请选择">
              <el-option v-for="item in userList" :key="item.id" :label="item.id + ' - ' + item.nickName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="bindUser">绑 定</el-button>
            <el-button @click="closeBindSampleDialog">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog :visible.sync="notifyExpressSampleDialog.visible" title="呼叫快递" width="500px"
        :before-close="closeExpressDialog">
        <el-form ref="expressFormRef" :model="notifyExpressSampleFormData" :rules="rules" label-width="100px">
          <el-form-item label="是否虚拟寄件" prop="virtual">
            <el-radio v-model="notifyExpressSampleFormData.virtual" label="true">是</el-radio>
            <el-radio v-model="notifyExpressSampleFormData.virtual" label="false">否</el-radio>
          </el-form-item>
          <el-form-item label="寄件人姓名" prop="name">
            <el-input v-model="notifyExpressSampleFormData.name" placeholder="请输入用户姓名" />
          </el-form-item>
          <el-form-item label="寄件人电话" prop="phone">
            <el-input v-model="notifyExpressSampleFormData.phone" placeholder="请输入用户手机号" />
          </el-form-item>
          <el-form-item label="寄件地址" prop="addr">
            <el-cascader :options="options" v-model="selectedOptions" @change="changeExpressArea"></el-cascader>
          </el-form-item>
          <el-form-item label="详细地址" prop="addrExt">
            <el-input v-model="notifyExpressSampleFormData.addr" type="textarea" :autosize="{ minRows: 4 }"
              placeholder="请输入详细地址" />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="notifyExpress">绑 定</el-button>
            <el-button @click="closeExpressDialog">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog :visible.sync="uploadFastqDialog.visible" :title="uploadFastqDialog.title" width="500px"
        :before-close="closeUploadFastqDialog">
        <el-form ref="uploadFastqFormRef" :model="uploadFastqFormData" :rules="rules" label-width="120px">
          <el-form-item label="fastq1文件信息" prop="fastq1">
            <el-input v-model="uploadFastqFormData.fastq1" placeholder="请输入fastq1文件信息" />
          </el-form-item>
          <el-form-item label="fastq2文件信息" prop="fastq2">
            <el-input v-model="uploadFastqFormData.fastq2" placeholder="请输入fastq2文件信息" />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="uploadFastq">确 定</el-button>
            <el-button @click="closeUploadFastqDialog">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 审核样本 -->
      <el-dialog :visible.sync="auditDialog.visible" :title="auditDialog.title" width="500px"
        :before-close="closeAuditDialog">
        <el-form ref="auditFormRef" :model="auditFormData" :rules="rules" label-width="120px">
          <el-form-item label="问题描述" prop="auditResult" v-show="!auditPass">
            <el-input v-model="auditFormData.auditResult" type="textarea" :autosize="{ minRows: 8 }"
              placeholder="请输入问题描述" />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="info" @click="auditPass = false" v-show="auditPass">存在问题</el-button>
            <el-button type="primary" @click="auditSample" v-show="auditPass">审核通过</el-button>
            <el-button type="primary" @click="auditSample" v-show="!auditPass">确 认</el-button>
            <el-button @click="closeAuditDialog">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 查看文件 -->
      <el-dialog :visible.sync="viewFileVisible" title="查看文件" width="1500px">
        <div class="viewFileVisible_box">
          <div class="input_file">
            <div class="input_file_top">
              <h3>输入文件</h3>
              <el-button type="warning" @click="unloadInputFlie()">上传文件</el-button>
            </div>

            <el-table :data="inputFileData" border style="width: 100%" max-height="500">
              <el-table-column prop="path" label="文件路径"></el-table-column>
              <el-table-column prop="suffix" label="文件类型"></el-table-column>
            </el-table>
          </div>

          <div class="output_file">
            <div class="input_file_top">
              <h3>输出文件</h3>
              <el-button type="warning">上传文件</el-button>
            </div>
            <el-table :data="outputFileData" border style="width: 100%" max-height="500">
              <el-table-column prop="path" label="文件路径"></el-table-column>
              <el-table-column prop="suffix" label="文件类型"></el-table-column>
            </el-table>
          </div>
        </div>
      </el-dialog>
      <el-dialog width="400px" :visible.sync="uploadFileVisible" title="上传文件">
        <el-upload class="upload-dialog" ref="upload" :action="uploadAction" :show-file-list="false"
          :on-change="submitUpload" :on-success="uploadFileSuccess" :headers="headers" :auto-upload="false">
          <el-button slot="trigger" style="margin-left: 5px;" type="success">上传Excel文件</el-button>
          <div slot="tip" class="el-upload__tip"></div>
        </el-upload>
      </el-dialog>

      <el-dialog width="400px" :visible.sync="uploadReportPdfVisible" title="模拟上传样本报告">
        <p>此操作为模拟上传样本报告，真实环境中是由报告系统自动上传用户样本报告。该操作会导致样本状态变更，请谨慎操作！</p>
        <el-upload class="upload-dialog" ref="uploadReport" :action="uploadReportPdfAction" :show-file-list="false"
          :on-change="submitUploadReport" :on-success="uploadReportFileSuccess" :headers="headers" :auto-upload="false">
          <el-button slot="trigger" style="margin-left: 5px;" type="success">上传样本报告</el-button>
          <div slot="tip" class="el-upload__tip"></div>
        </el-upload>
      </el-dialog>

      <el-dialog width="800px" :visible.sync="surveyDialog.visible" :title="surveyDialog.title">
        <el-form ref="survyFormRef" :rules="rules" label-width="120px">
          <div v-for="(data, index) in surveyObj.pageQuestions" :key="data.id"
            style="margin-top: 10px; padding-left: 2%; padding-right: 2%;">
            <label>
              <span style="font-size: 16px;">{{ (index + 1) + '、' + data.title }}</span>
              <span style="margin-left: 5px;">【{{ typeMap[data.type] }}】</span>
            </label>
            <div style="margin-top: 10px; padding-left: 2%; padding-right: 2%;">
              <template v-if="data.type == 'EXCLUSIVE_CHOICE'">
                <el-radio v-model="answerFormData[index].answer" v-for="(option) in data.options" :key="option.id"
                  :label="option.id">{{ option.title }}</el-radio>
              </template>
              <template v-if="data.type == 'MULTIPLE_CHOICE'">
                <el-checkbox v-model="answerFormData[index].answer[j]" v-for="(option, j) in data.options"
                  :key="option.id">{{ option.title }}</el-checkbox>
              </template>
              <template v-if="data.type == 'TEXTAREA'">
                <el-input v-model="answerFormData[index].answer" placeholder="请输入内容"></el-input>
              </template>
            </div>
          </div>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="saveSurveyDialog">保 存</el-button>
            <el-button @click="closeSurveyDialog">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </template>

    <sampleDetailDesign :checkedSample="checkedSample" v-if="showDetailIndex" @close="closeDetail"></sampleDetailDesign>

  </div>
</template>

<script>
import sampleDetailDesign from '@/views/aliyun/detection/sample/detail'
import { Session } from '@/utils/storage'
import sampleApi from '@/api/aliyun/detection/sample'
import sampleHistoryApi from '@/api/aliyun/detection/sample/history'
import expressApi from '@/api/aliyun/detection/express'
import userApi from '@/api/system/user'
import { formatDate } from '@/utils/formatTime'
import surveyApi from '@/api/aliyun/questionnaire/survey'
import answerApi from '@/api/aliyun/questionnaire/answer'
import applicationApi from '@/api/system/application'
import { provinceAndCityData, regionData, codeToText } from 'element-china-area-data'
import tenantApi from '@/api/system/tenant'

export default {
  name: 'sampleIndex',
  components: {
    sampleDetailDesign
  },
  data() {
    return {
      queryParams: {
        sampleNumber: '',
        pageNum: 0,
        pageSize: 10,
        status: '',
      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      userList: [],
      dialog: {},
      formData: {
        num: 1
      },
      rules: {},

      detailDialog: {},
      checkedSample: {},
      sampleImgUrl: '',

      uploadFastqDialog: {},
      uploadFastqFormData: {},

      auditDialog: {},
      auditFormData: {},

      statusMap: {
        CREATE: '已创建',
        TO_BE_SENT_OUT: '待寄出',
        SENT_OUT: '已寄出',
        SAMPLE_RECEIVE: '样本已收到',
        REPORT_SEQ_END: '实验室测序完成',
        DATA_ANALYSIS: '数据分析中',
        REPORT_AUDIT: '样本审核中',
        COMPLETED: '完成',
      },

      vipCardStatusMap: {
        NON_BIND: '未绑定',
        BIND: '已绑定',
      },

      bindSampleDialog: {},
      bindSample: {},
      bindSampleFormData: {},

      notifyExpressSampleDialog: {},
      notifyExpressSample: {},
      notifyExpressSampleFormData: {},

      expressBaseAddr: '',
      addrExtInfo: '',
      options: regionData,
      selectedOptions: [],

      auditPass: true,
      viewFileVisible: false,
      inputFileData: [],
      outputFileData: [],
      viewFileSampleId: "",
      uploadAction: '',
      uploadFileVisible: false,
      headers: {},

      uploadReportPdfVisible: false,
      uploadReportPdfAction: '',

      detailProcessDialog: {},
      activeStep: 0,
      sampleHistoryTimeMap: {},

      saleUserList: [],
      saleUserMap: {},
      surveyDialog: {},
      surveyObj: {},
      typeMap: {
        EXCLUSIVE_CHOICE: '单选',
        MULTIPLE_CHOICE: '多选',
        TEXTAREA: '填空',
      },
      answerFormData: [],
      optionTitleMap: {},
      answerId: null,
      showDetailIndex: false,

      isAdmin: false,
      tenantList: [],
    };
  },
  mounted() {
    this.headers = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    };
    let userInfo = this.$store.state.userInfos.userInfos;
    let roleList = userInfo.roleList;
    if (roleList && roleList.length != 0) {
      roleList.forEach(v => {
        if (v.enName == "ADMIN") {
          this.isAdmin = true;
          return;
        }
      })
    }
  },
  methods: {
    closeDetail() {
      this.showDetailIndex = false;
    },
    saveSurveyDialog() {
      let answerJsonArr = [];
      let index = 0;
      this.surveyObj.pageQuestions.forEach(v => {
        let type = v.type;
        let answer = {};
        if (type === 'EXCLUSIVE_CHOICE') {
          answer = {
            id: this.answerFormData[index].answer,
            title: this.optionTitleMap[v.id + '-' + this.answerFormData[index].answer].optionTitle
          }
        } else if (type === 'MULTIPLE_CHOICE') {
          answer = [];
          for (let i = 0, len = this.answerFormData[index].answer.length; i < len; i++) {
            if (this.answerFormData[index].answer[i]) {
              answer.push({
                id: v.options[i].id,
                title: v.options[i].title
              });
            }
          }
        } else {
          answer = this.answerFormData[index].answer;
        }
        answerJsonArr.push({
          id: v.id,
          title: v.title,
          type: v.type,
          answer: answer
        })
        index++;
      })
      answerApi.add({
        id: this.answerId,
        surveyId: this.surveyObj.id,
        sampleId: this.checkedSample.id,
        contentJson: JSON.stringify(answerJsonArr)
      }).then(res => {
        this.$message({ message: '样本问卷保存成功！', type: 'success' });
        this.closeSurveyDialog();
      })
    },
    closeSurveyDialog() {
      this.$set(this.surveyDialog, 'visible', false);
    },
    openSurveyDialog(row) {
      this.checkedSample = row;
      answerApi.getBySampleId(row.id).then(resp => {
        let contentJson = resp.data.contentJson;
        this.answerId = resp.data.id;
        let contentJsonMap = {};
        if (contentJson) {
          contentJson = JSON.parse(contentJson);
          contentJson.forEach(contentJsonV => {
            contentJsonMap[contentJsonV.id] = contentJsonV.answer;
          })
        }

        applicationApi.getType('MBIOLANCE_UI').then(res => {
          let extJson = res.data.extJson;
          let obj = JSON.parse(extJson);
          let surveyId = obj.surveyId;
          this.answerFormData = []
          surveyApi.detail(surveyId).then(r => {
            this.surveyObj = r.data

            r.data.pageQuestions.forEach(v2 => {
              let answer = null;
              if (v2.type === 'EXCLUSIVE_CHOICE') {
                if (contentJsonMap[v2.id]) {
                  answer = contentJsonMap[v2.id].id;
                } else {
                  answer = -1;
                }
              } else if (v2.type === 'MULTIPLE_CHOICE') {
                answer = [];
                if (contentJsonMap[v2.id]) {
                  let multiAnswerMap = {}
                  if (contentJsonMap[v2.id] && contentJsonMap[v2.id].length != 0) {
                    contentJsonMap[v2.id].forEach(multiAnswer => {
                      multiAnswerMap[multiAnswer.id] = true;
                    })
                    v2.options.forEach(mulV2Option => {
                      if (multiAnswerMap[mulV2Option.id]) {
                        answer.push(true);
                      } else {
                        answer.push(false)
                      }
                    })
                  }
                }
              } else {
                answer = contentJsonMap[v2.id] ? contentJsonMap[v2.id] : ''
              }
              this.answerFormData.push({
                answer: answer
              })
              if (v2.options) {
                v2.options.forEach(op => {
                  this.optionTitleMap[v2.id + '-' + op.id] = {
                    optionTitle: op.title
                  }
                })
              }
            })
            this.$set(this.surveyDialog, 'visible', true);
            this.$set(this.surveyDialog, 'title', '填写/编辑问卷');
          })
        })
      })

    },
    exportSample() {
      sampleApi.exportAvailableNumberList().then(res => {
        let blob = new Blob([res], { type: 'application/vnd.ms-excel' });
        // 创建新的URL并指向File对象或者Blob对象的地址
        const blobURL = window.URL.createObjectURL(blob)
        // 创建a标签，用于跳转至下载链接
        const tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', '样本编号.xlsx')
        // 兼容：某些浏览器不支持HTML5的download属性
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        // 挂载a标签
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        // 释放blob URL地址
        window.URL.revokeObjectURL(blobURL)
      })
    },
    setAvailable(row) {
      sampleApi.setAvailable(row.id).then(res => {
        this.$message({ message: '样本可用设置成功！', type: 'success' });
        this.handleQuery();
      })
    },
    updateStatus() {
      this.handleQuery();
    },
    openDetailProcess(row) {
      this.checkedSample = row;
      this.showDetailIndex = true;

    },
    closeDetailProcessDialog() {
      this.$set(this.detailProcessDialog, 'visible', false);
    },
    openDataSyncDialog(row) {
      this.$confirm('此操作为模拟数据同步，确认之后，样本状态将发生变更, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        sampleApi.mockSyncSample(row.id).then(res => {
          this.$message({ message: '模拟样本同步成功！', type: 'success' });
          this.handleQuery();
        })
      }).catch(() => {
        this.$message.error('已取消操作！');
      });
    },
    openUploadReportDialog(row) {
      this.uploadReportPdfVisible = true;
      this.uploadReportPdfAction = process.env.VUE_APP_FILE_API_PREV + '/sample/mock-upload-report/' + row.id;
    },
    uploadReportFileSuccess() {
      this.uploadReportPdfVisible = false;
      this.$message({ message: '文件上传成功！', type: 'success' });
      this.handleQuery();
    },
    submitUploadReport() {
      this.$refs.uploadReport.submit();
    },
    // 查看文件
    viewFile(id) {
      this.viewFileSampleId = id;
      this.viewFileVisible = true;
      sampleApi.getFileList(this.viewFileSampleId).then(res => {
        let fileData = res.data;
        let outOutData = [];
        let inputData = [];
        fileData.forEach((i) => {
          if (i.fileType == "OUTPUT") {
            outOutData.push(i)
          }
          if (i.fileType == "INPUT") {
            inputData.push(i);
          }
        })
        this.outputFileData = outOutData;
        this.inputFileData = inputData;
      })
    },
    unloadInputFlie() {
      this.uploadFileVisible = true;
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    uploadFileSuccess() {
      this.uploadFileVisible = false;
      this.$message({ message: '文件上传成功！', type: 'success' });
      this.handleQuery();
    },
    auditSample() {
      let auditPass = this.auditPass;
      sampleApi.auditSample({
        id: this.checkedSample.id,
        auditPass: auditPass,
        auditResult: this.auditFormData.auditResult,
      }).then(res => {
        this.$message({ message: '样本审核完成！', type: 'success' });
        this.$set(this.auditDialog, 'visible', false);
        this.handleQuery();
      })
    },
    openAuditDialog(row) {
      this.$set(this.auditDialog, 'visible', true);
      this.$set(this.auditDialog, 'title', '审核样本');
      this.checkedSample = row;
    },
    closeAuditDialog() {
      this.$set(this.auditDialog, 'visible', false);
    },
    uploadFastq() {
      let uploadFastqFormData = this.uploadFastqFormData;
      uploadFastqFormData.id = this.checkedSample.id;
      sampleApi.uploadSampleFastq(uploadFastqFormData).then(res => {
        this.$message({ message: 'fastq文件上传成功！', type: 'success' });
        this.$set(this.uploadFastqDialog, 'visible', false);
        this.handleQuery();
      })
    },
    closeUploadFastqDialog() {
      this.$set(this.uploadFastqDialog, 'visible', false);
    },
    openUploadFastqDialog(row) {
      this.$set(this.uploadFastqDialog, 'visible', true);
      this.$set(this.uploadFastqDialog, 'title', '上传fastq文件');
      this.checkedSample = row;
    },
    goDesignReport(row) {
      let url = this.$router.resolve({
        path: "/reporting/reportDesign",
        query: { number: row.number }
      })
      window.open(url.href, '_blank');
    },
    openDetail(row, column) {
      if (column.property == "number") {
        this.$set(this.detailDialog, 'visible', true);
        this.$set(this.detailDialog, 'title', '样本详情');
        this.checkedSample = row;
        this.sampleImgUrl = 'https://w66h994817.zicp.fun/platform/aliyun-api/sample/gene-barcode/' + row.number
      }
    },
    labSignDialog(row) {
      sampleApi.signSample(row.number).then((res) => {
        this.$message({ message: '样本签收成功！', type: 'success' });
        this.handleQuery();
      });
    },
    cancelExpress(row) {
      expressApi.cancel(row.id).then(res => {
        this.$message({ message: '样本快递已取消成功！', type: 'success' });
        this.handleQuery();
      })
    },
    notifyExpress() {
      let params = {
        sampleId: this.notifyExpressSample.id,
        name: this.notifyExpressSampleFormData.name,
        phone: this.notifyExpressSampleFormData.phone,
        addr: this.expressBaseAddr + this.notifyExpressSampleFormData.addr,
        addrExtInfo: JSON.stringify(this.addrExtInfo),
        virtual: this.notifyExpressSampleFormData.virtual,
      };
      expressApi.add(params).then(res => {
        this.$message({ message: '样本呼叫快递成功！', type: 'success' });
        this.$set(this.notifyExpressSampleDialog, 'visible', false);
        this.handleQuery();
      })
    },
    changeExpressArea(vals) {
      this.expressBaseAddr = codeToText[vals[0]] + codeToText[vals[1]] + codeToText[vals[2]];
      this.addrExtInfo = vals;
    },
    openExpressDialog(row) {
      this.notifyExpressSample = row;
      this.$set(this.notifyExpressSampleDialog, 'visible', true);
    },
    closeExpressDialog() {
      this.$set(this.notifyExpressSampleDialog, 'visible', false);
    },
    bindUser() {
      sampleApi.bindSysUser({
        number: this.bindSample.number,
        phone: this.bindSampleFormData.phone,
        userName: this.bindSampleFormData.userName,
        sysUserId: this.bindSampleFormData.sysUserId,
      }).then(res => {
        this.$message({ message: '样本绑定成功！', type: 'success' });
        this.$set(this.bindSampleDialog, 'visible', false);
        this.handleQuery();
      })
    },
    openBindSampleDialog(row) {
      this.bindSample = row;
      this.$set(this.bindSampleDialog, 'visible', true);
    },
    closeBindSampleDialog() {
      this.$set(this.bindSampleDialog, 'visible', false);
    },
    handleQuery() {
      this.loading = true;
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize,
        statuses: this.queryParams.status == '' ? [] : [this.queryParams.status],
        sampleNumber: this.queryParams.sampleNumber,
      };
      sampleApi.page(params).then((res) => {
        let data = res.data;
        let index = 1
        data.content.forEach((v) => {
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
          v.statusText = this.statusMap[v.status];
          v.auditPassText = v.auditPass != null ? (v.auditPass ? '审核通过' : '审核不通过') : '-'
          if (v.vipCardNumber) {
            v.vipCardInfo = v.vipCardNumber + '【' + this.vipCardStatusMap[v.vipCardStatus] + '】'
          }
          v.dataIndex = index++;
        });
        this.dataList = data.content;

        this.total = data.count;
        this.loading = false;
      }).catch(() => { });
    },
    resetQuery() {
      this.queryParams = {
        sampleNumber: '',
        pageNum: 0,
        pageSize: 10,
        status: '',
      };
      this.handleQuery();
    },

    addOrUpdate() {
      let that = this;
      if (this.formData.id) {
        sampleApi.update({
          id: this.formData.id,
          saleUserId: this.formData.saleUserId,
          saleUserName: this.saleUserMap[this.formData.saleUserId],
          productType: this.formData.productType,
          sampleUses: this.formData.sampleUses,
          customName: this.formData.customName,
          saleRemark: this.formData.saleRemark,
          tenantId: this.formData.tenantId
        }).then((res) => {
          this.$message({ message: '样本更新成功！', type: 'success' });
          that.closeDialog();
        });
      } else {
        sampleApi.add({
          saleUserId: this.formData.saleUserId,
          saleUserName: this.saleUserMap[this.formData.saleUserId],
          num: this.formData.num,
          productType: this.formData.productType,
          sampleUses: this.formData.sampleUses,
          customName: this.formData.customName,
          saleRemark: this.formData.saleRemark,
          tenantId: this.formData.tenantId
        }).then((res) => {
          this.$message({ message: '样本添加成功！', type: 'success' });
          this.closeDialog();
        });
      }
    },
    openDialog(id) {
      let that = this;
      that.saleUserList = [];
      userApi.listByRole('SALE_ROLE').then(res => {
        res.data.forEach(v1 => {
          v1.id = v1.id + '';
          that.saleUserMap[v1.id] = v1.name;
          that.saleUserList.push(v1)
        })
        tenantApi.list().then(tRes => {
          this.tenantList = tRes.data;
          this.$set(this.dialog, 'visible', true);
          if (id) {
            this.$set(this.dialog, 'title', '编辑样本');
            sampleApi.get(id).then((res) => {
              let data = res.data;
              that.formData = data;
            });
          } else {
            this.$set(this.dialog, 'title', '新增样本');
            that.formData = {
              num: 1
            };
            // sampleApi.add({
            //   saleUserId: this.formData.saleUserId,
            //   saleUserName: this.saleUserMap[this.formData.saleUserId],
            //   num: 1,
            // }).then((res) => {
            //   this.$message({ message: '样本添加成功！', type: 'success' });
            //   this.handleQuery();
            // });
          }
        })
        
      })
    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.handleQuery();
    },
    // 删除样本
    handleDelete(id) {
      this.$confirm("确定删除该数据, 是否继续?", "提示", {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        if (id) {
          sampleApi.delete(id).then((res) => {
            this.$message.success('样本删除成功！');
            this.handleQuery();
          });
        } else {
          this.$message.error('暂不支持批量删除样本！');
        }
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' });
      });
    },
    closeDetailDialog() {
      this.$set(this.detailDialog, 'visible', false);
      this.$set(this.detailDialog, 'title', '');
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (column.property == "number") {
        return {
          "cursor": "pointer"
        }
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSelectionRoleChange(rows) {
      if (rows) {
        let arr = [];
        rows.forEach((v) => {
          arr.push(v.id);
        });
        this.selectRoleIdArr = arr;
      }
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
  },
  created() {
    userApi.list().then((res) => {
      let data = res.data;
      this.userList = data;
    })
    this.handleQuery();
  }
};
</script>

<style scoped>
.block {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}

.viewFileVisible_box {
  display: flex;
}

.input_file {
  width: 50%;
  border: 1px solid #DCDFE6;
  padding: 2% 1%;
  margin-right: 2%;
}

.input_file h3 {
  /* margin-bottom: 2%; */
}

.output_file {
  width: 50%;
  border: 1px solid #DCDFE6;
  padding: 2%;
}

.output_file h3 {
  /* margin-bottom: 2%; */
}

.input_file_top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 2%;
}
</style>